package cn.acewill.yxd.yunxundian.ui.user;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.componet.MyProgressBar;
import cn.acewill.yxd.yunxundian.model.ManagerEfficBean;
import cn.acewill.yxd.yunxundian.pubClass.OkHttpManger;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.sign.EvaluationByMonthActivity;

/**
 * Created by AAA on 2017/4/11.
 */

public class ManageEfficMainActivity extends BaseActivity{

    private MyProgressBar scaleProgress,dayWorkProgress,projectTaskProgress,customTaskProgress,appointTaskProgress;
    private TextView userName;
    private TextView storeNum;
    private TextView avgForStore;
    private TextView avgForDay;
    private TextView delayTask;
    private TextView avgDelayTask;
    private TextView progressTitle;
    private TextView scaleTask;
    private TextView dayWork;
    private TextView projectTask;
    private TextView customTask;
    private TextView appointTask;
    private String firstName;
    private TextView nonetwork;
    private int userId;
    /*年月*/
    private int year,month;
    private double scaleMax,projectMax,oppintMax,customMax,dayMax;
    private Toolbar myTooolBar;
    private LinearLayout myLiner;
    private RelativeLayout loadingView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.manage_effic_main);
        initView();
    }

    public void initView(){
        initToolbar();
        this.nonetwork= (TextView) findViewById(R.id.noNetWork);
        firstName=getIntent().getStringExtra("userName");
        month=getIntent().getIntExtra("month",0);
        year=getIntent().getIntExtra("year",0);
        userId=getIntent().getIntExtra("userId",-1);
        TextView textTitle = (TextView) findViewById(R.id.textTitle);
        textTitle.setText(year+"年"+month+"月");

        TextView lookInfo = (TextView) findViewById(R.id.lookInfo);
        lookInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ManageEfficMainActivity.this
                        , EvaluationByMonthActivity.class)
                        .putExtra("year",year)
                        .putExtra("month",month)
                        .putExtra("userId",userId)
                        .putExtra("userName",firstName));
            }
        });

        /*progress*/
        this.scaleProgress= (MyProgressBar) findViewById(R.id.scaleProgress);
        this.dayWorkProgress= (MyProgressBar) findViewById(R.id.dayWorkProgress);
        this.projectTaskProgress= (MyProgressBar) findViewById(R.id.projectTaskProgress);
        this.customTaskProgress= (MyProgressBar) findViewById(R.id.customTaskProgress);
        this.appointTaskProgress= (MyProgressBar) findViewById(R.id.appointTaskProgress);
        /*text*/
        this.userName= (TextView) findViewById(R.id.userName);
        this.storeNum= (TextView) findViewById(R.id.storeNum);
        this.avgForStore= (TextView) findViewById(R.id.avgForStore);
        this.avgForDay= (TextView) findViewById(R.id.avgForDay);
        this.delayTask= (TextView) findViewById(R.id.delayTask);
        this.avgDelayTask= (TextView) findViewById(R.id.avgDelayTask);
        /*任务完成度*/
        this.progressTitle= (TextView) findViewById(R.id.progressTitle);
        this.scaleTask= (TextView) findViewById(R.id.scaleTask);
        this.dayWork= (TextView) findViewById(R.id.dayWork);
        this.projectTask= (TextView) findViewById(R.id.projectTask);
        this.customTask= (TextView) findViewById(R.id.customTask);
        this.appointTask= (TextView) findViewById(R.id.appointTask);
        myLiner= (LinearLayout) findViewById(R.id.myLiner);
        loadingView= (RelativeLayout) findViewById(R.id.loadingRel);
        setVisibleOrGone(1);
    }

    private void initToolbar(){
        this.myTooolBar= (Toolbar) findViewById(R.id.myToolBar);
        myTooolBar.setTitle("");
        myTooolBar.setNavigationIcon(R.mipmap.back);
        setSupportActionBar(myTooolBar);
        myTooolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    /*请求获取个人信息*/
    public void LoadInfo(){
        Map<String,String> map=new HashMap<>();
        map.put("task","getEmployeeSchKPI");
        map.put("empid", userId+"");
        map.put("year",year+"");
        map.put("month",month+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] strings=result.split("\\|");
                    if(strings[0].equals("201")){
                        Toast.makeText(ManageEfficMainActivity.this,strings[1],Toast.LENGTH_SHORT).show();
                    }else {
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<ArrayList<ManagerEfficBean>>() {
                        }.getType();
                        ArrayList<ManagerEfficBean>  melist=gson.fromJson(pubClass.convertToArrayJson(result),typeList);
                        for(int i=0;i<melist.size();i++){
                            ManagerEfficBean bean=new ManagerEfficBean();
                            bean=melist.get(i);
                            userName.setText(firstName);
                            storeNum.setText(bean.getMendianshuliang());
                            avgForStore.setText(String.valueOf(changeDouble(Double.parseDouble(bean.getPingjundandian()))));
                            avgForDay.setText(String.valueOf(changeDouble(Double.parseDouble(bean.getPingjundantian()))));
                            delayTask.setText(String.valueOf(changeDouble(Double.parseDouble(bean.getYanwurenwu()))));
                            avgDelayTask.setText(String.valueOf(changeDouble(Double.parseDouble(bean.getPingjunyanwutianshu()))));
                            LoadTaksinfo();
                        }
                    }
                }
                @Override
                public void onFailture() {
                    setVisibleOrGone(3);
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*请求获取任务完成度*/
    public void LoadTaksinfo(){
        Calendar ca=Calendar.getInstance();
        Map<String,String> map=new HashMap<>();
        map.put("task","getEmployeeSchFenlei");
        map.put("empid", userId+"");
        map.put("year",year+"");
        map.put("month",month+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] strings=result.split("\\|");
                    setVisibleOrGone(2);
                    if(strings[0].equals("201")){
                        Toast.makeText(ManageEfficMainActivity.this,strings[1],Toast.LENGTH_SHORT).show();
                    }else {
                        JSONArray array=JSONArray.parseArray(pubClass.convertToArrayJson(result));
                        for (int i=0;i<array.size();i++){
                            JSONObject obj=array.getJSONObject(i);
                            progressTitle.setText("月度事件完成度");
                            scaleTask.setText(obj.getString("餐厅任务done")+"/"+obj.getString("餐厅任务max"));
                            dayWork.setText(obj.getString("日常任务done")+"/"+obj.getString("日常任务max"));
                            projectTask.setText(obj.getString("项目任务done")+"/"+obj.getString("项目任务max"));
                            customTask.setText(obj.getString("自定义任务done")+"/"+obj.getString("自定义任务max"));
                            appointTask.setText(obj.getString("上司委派done")+"/"+obj.getString("上司委派max"));
                            //每个progressbar的值
                            if(Double.parseDouble(obj.getString("餐厅任务done"))<=0&&Double.parseDouble(obj.getString("餐厅任务max"))<=0){
                                scaleMax=0;
                            }else{
                                scaleMax = changeDouble(Double.parseDouble(obj.getString("餐厅任务done"))/Double.parseDouble(obj.getString("餐厅任务max"))*100);
                            }
                            if(Double.parseDouble(obj.getString("日常任务done"))<=0&&Double.parseDouble(obj.getString("日常任务max"))<=0){
                                dayMax=0;
                            }else{
                                dayMax = changeDouble(Double.parseDouble(obj.getString("日常任务done"))/Double.parseDouble(obj.getString("日常任务max"))*100);
                            }
                            if(Double.parseDouble(obj.getString("项目任务done"))<=0&&Double.parseDouble(obj.getString("项目任务max"))<=0){
                                projectMax=0;
                            }else{
                                projectMax = changeDouble(Double.parseDouble(obj.getString("项目任务done"))/Double.parseDouble(obj.getString("项目任务max"))*100);
                            }
                            if(Double.parseDouble(obj.getString("自定义任务done"))<=0&&Double.parseDouble(obj.getString("自定义任务max"))<=0){
                                customMax=0;
                            }else{
                                customMax = changeDouble(Double.parseDouble(obj.getString("自定义任务done"))/Double.parseDouble(obj.getString("自定义任务max"))*100);
                            }
                            if(Double.parseDouble(obj.getString("上司委派done"))<=0&&Double.parseDouble(obj.getString("上司委派max"))<=0){
                                oppintMax=0;
                            }else{
                                oppintMax = changeDouble(Double.parseDouble(obj.getString("上司委派done"))/Double.parseDouble(obj.getString("上司委派max"))*100);
                            }
                            scaleProgress.setProgress((int)scaleMax);
                            dayWorkProgress.setProgress((int)dayMax);
                            projectTaskProgress.setProgress((int)projectMax);
                            customTaskProgress.setProgress((int)customMax);
                            appointTaskProgress.setProgress((int)oppintMax);
                        }
                    }
                }
                @Override
                public void onFailture() {
                  setVisibleOrGone(3);
                }
            },map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public double changeDouble(Double dou){
        NumberFormat nf=new DecimalFormat( "0.0 ");
        dou = Double.parseDouble(nf.format(dou));
        return dou;
    }

    //接收网络状态的判断广播
    NetWorkStateReceiver netWorkStateReceiver;
    int whetherConnectNetWork=0;
    @Override
    protected void onResume() {
        if (netWorkStateReceiver==null){
            netWorkStateReceiver=new NetWorkStateReceiver();
        }
        IntentFilter filter=new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver,filter);
        System.out.print("广播注册");
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
        System.out.print("广播注销");
    }

    class NetWorkStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo!=null){
                whetherConnectNetWork=1;
                LoadInfo();
            }else{
                setVisibleOrGone(3);
            }
        }
    }
    public void setVisibleOrGone(int k){
        if (k==1){
            loadingView.setVisibility(View.VISIBLE);
            myLiner.setVisibility(View.GONE);
            nonetwork.setVisibility(View.GONE);
        }
        if (k==2){
            loadingView.setVisibility(View.GONE);
            myLiner.setVisibility(View.VISIBLE);
            nonetwork.setVisibility(View.GONE);
        }
        if (k==3){
            nonetwork.setVisibility(View.VISIBLE);
            loadingView.setVisibility(View.GONE);
        }
    }
}
